﻿using yao.Entity;
using yao.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using Titan;

namespace yao.website.Controllers
{
    /// <summary>
    /// 供应商管理
    /// </summary>
    public class ProviderController : BaseController
    {
        public ActionResult Index(int? p)
        {
            int pageIndex = p == null ? 1 : (int)p;
            ViewBag.PageIndex = pageIndex;

            //为提高性能，需要时才打开数据库，后面还会有一次数据库验证 
            using (IDbSession cn = OpenSession())
            {
                QueryExpression q = new QueryExpression();
                q.EntityType = typeof(Provider);
                q.Selects.Add(Provider_.ProviderId);//唯一Id
                q.Selects.Add(Provider_.CompanyName);//公司简称
                q.Selects.Add(Provider_.FullName);//公司全称
                q.Selects.Add(Provider_.CompanyNo);//客户编号
                q.Selects.Add(Provider_.ContactName);//联系人
                q.Selects.Add(Provider_.Address);//地址
                q.Selects.Add(Provider_.AccountPayables);//应付账款
                q.Selects.Add(Provider_.NotCompletedOrderCount);//未完成订单数
                q.Selects.Add(Provider_.Email);//邮箱
                q.Selects.Add(Provider_.Mb);//手机号
                q.Selects.Add(Provider_.AreaId);//所属区域
                q.Selects.Add(Provider_.EmployeeId);//负责人
                q.Selects.Add(Provider_.Employee.EmployeeName);//负责人
                q.Selects.Add(Provider_.IsActive);//启用状态
                q.Wheres.Add(Provider_.CompanyId.TEqual(CurrentEmployee.CompanyId));
                q.OrderBy(Provider_.ProviderId.Desc);
                q.PageSize = 20;
                q.PageIndex = pageIndex;
                q.ReturnMatchedCount = true;
                Providers providers = new Providers();
                providers.TotalCount = cn.SelectCollection(providers.Items, q);
                return View(providers);
            }
        }

        #region 编辑

        public ActionResult Edit(long? id)
        {
            Provider provider = new Provider();
            if (id != null)
            {
                ViewBag.Title = "修改供应商-" + id;
                provider.ProviderId = (long)id;
                using (IDbSession cn = OpenSession())
                {
                    cn.Select(provider,Provider_.ALL,Provider_.Employee.EmployeeName);
                }
            }
            else
            {
                provider.AreaId = CurrentEmployee.AreaId;
            }

            return View(provider);
        }
        [HttpPost]
        public ActionResult Edit(long? id, Provider provider)
        {
            #region 验证
            Validate(provider, Provider_.CompanyNo);
            Validate(provider, Provider_.CompanyName);
            Validate(provider, Provider_.FullName);
            Validate(provider, Provider_.ContactName);
            Validate(provider, Provider_.Mb);
           
            if (provider.AreaId!=null&&!ApplicationCache.IsValidAreaId((long)provider.AreaId))
            {
                AddFormError(Provider_.AreaId, "所属地区无效");
            }
            #endregion


            if (!IsValid)
            {
                return View(provider);
            }


            using (IDbSession cn = OpenSession())
            {
                if (id == null)//添加
                {
                    provider.CompanyId = CurrentEmployee.CompanyId;//必须先赋值才能后续验证

                    #region validate
                    ConditionExpressionCollection cs = new ConditionExpressionCollection();
                    cs.Add(Provider_.CompanyId.TEqual(CurrentEmployee.CompanyId));
                    cs.Add(Provider_.CompanyNo.TEqual(provider.CompanyNo));
                    if (cn.Exists<Provider>(cs))
                    {
                        AddFormError(Provider_.CompanyNo, "公司编号不允许重复");
                    }
                    if (!IsValid) return View(provider);

                    cs = new ConditionExpressionCollection();
                    cs.Add(Provider_.CompanyId.TEqual(CurrentEmployee.CompanyId));
                    cs.Add(Provider_.CompanyName.TEqual(provider.CompanyName));
                    if (cn.Exists<Provider>(cs))
                    {
                        AddFormError(Provider_.CompanyName, "公司名称不允许重复");
                    }
                    if (!IsValid) return View(provider);
                    #endregion
                    
                    provider.GlobalCompanyId = 0;
                    provider.IsActive = true;
                    provider.CreateTime = DateTime.Now;
                    cn.Insert(provider);
                }
                else
                {
                    provider.ProviderId = id.Value;

                    #region validate
                    ConditionExpressionCollection cs = new ConditionExpressionCollection();
                    cs.Add(Provider_.CompanyId.TEqual(CurrentEmployee.CompanyId));
                    cs.Add(Provider_.CompanyNo.TEqual(provider.CompanyNo));
                    cs.Add(Provider_.ProviderId.TNotEqual(provider.ProviderId));
                    if (cn.Exists<Provider>(cs))
                    {
                        AddFormError(Provider_.CompanyNo, "公司编号不允许重复");
                    }
                    if (!IsValid) return View(provider);

                    cs = new ConditionExpressionCollection();
                    cs.Add(Provider_.CompanyId.TEqual(CurrentEmployee.CompanyId));
                    cs.Add(Provider_.CompanyName.TEqual(provider.CompanyName));
                    cs.Add(Provider_.ProviderId.TNotEqual(provider.ProviderId));
                    if (cn.Exists<Provider>(cs))
                    {
                        AddFormError(Provider_.CompanyName, "公司名称不允许重复");
                    }
                    if (!IsValid) return View(provider);
                    #endregion

                      provider.UpdateTime = DateTime.Now;
                    cn.Update(provider, Provider_.AreaId, Provider_.ContactName,Provider_.CompanyName, Provider_.CompanyNo, Provider_.Email, Provider_.FullName,Provider_.GlobalCompanyId, Provider_.Mb,Provider_.EmployeeId,Provider_.Address,Provider_.UpdateTime,Provider_.CompanyCode);
                }
            }
            return new IframeResult(Url.Action("Edit"),Url.Action("Index"));
        }
        #endregion

        #region 删除

        [HttpPost]
        public ActionResult Delete(long providerId)
        {
            Provider provider = new Provider();
            provider.ProviderId = providerId;
            bool ret = false;
            using (IDbSession cn = OpenSession())
            { 
              ret= cn.Delete(provider) >0;
            }
            return Json(new { ret = ret });
        }
        #endregion

        #region 启用

        [HttpPost]
        public ActionResult Active(long providerId, bool isActive)
        {
            Provider provider = new Provider
            {
                ProviderId = providerId,
                IsActive=isActive
            };
            bool ret = false;
            using (IDbSession cn = OpenSession())
            {
                ret = cn.Update(provider, Provider_.IsActive) > 0;
            }
            return Json(new { ret = ret });
        }
        #endregion

        #region 详情

        public ActionResult Detail(long id)
        {
            using (IDbSession cn = OpenSession())
            {
                Provider provider = new Provider { ProviderId = id };
                cn.Select(provider, Provider_.ALL, Provider_.Employee.EmployeeName);
                return View(provider);
            }
        }

        #endregion
        

    }
}
